package cqrtplm.aop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.log.LogEventEnum;
import com.hustcad.plm.basic.log.TyplmLogger;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.doc.dto.CreateDocInputDTO;
import com.hustcad.plm.pdm.doc.dto.SaveDocDTO;
import com.hustcad.plm.pdm.doc.service.TyplmDocumentService;
import com.hustcad.plm.pdm.doc.vo.DocumentVO;
import com.hustcad.plm.pdm.file.model.dto.FileGroupDTO;
import com.hustcad.plm.pdm.filevault.model.vo.FileDataVO;
import com.hustcad.plm.pdm.folder.model.dto.HyperlinkDTO;
import com.hustcad.plm.pdm.folder.model.vo.SubfolderVO;
import com.hustcad.plm.pdm.folder.model.vo.SubfolderWebVO;
import com.hustcad.plm.pdm.folder.service.TyplmHyperlinkService;
import com.hustcad.plm.pdm.folder.service.TyplmSubFolderLinkService;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.audit.AuditLogDO;
import com.ty.basic.entity.folder.SubfolderDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.util.StringUtil;
import com.ty.basic.vo.TyAttributeDefMapVO;
import cqrtplm.common.CommonService;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.entity.ObjectStorageDO;
import cqrtplm.mapper.RTPartMapper;
import cqrtplm.mapper.StoragePlanningMapper;
import cqrtplm.service.DocFolderOperationService;
import cqrtplm.service.ObjectStorageService;
import cqrtplm.service.RTDocService;
import cqrtplm.vo.PDFProjectVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;


@Aspect
@Component
@Slf4j
@Order(Ordered.LOWEST_PRECEDENCE)
public class DocCreateAOP {
    @Resource
    private TyplmTypeService typlmTypeService;

    @Resource
    private TyplmLogger typlmLogger;

    @Resource
    private TyplmDocumentService typlmDocumentService;

    @Resource
    private DocFolderOperationService docFolderOperationService;

    @Resource
    private TyplmSubFolderLinkService typlmSubFolderLinkService;

    @Resource
    private TyplmHyperlinkService typlmHyperlinkService;

    @Resource
    private RTDocService docService;

    @Resource
    private StoragePlanningMapper storagePlanningMapper;

    @Resource
    private ObjectStorageService objectStorageService;

    @Resource
    private RTPartMapper rtPartMapper;

    @Value("${ipd.base.url:http://127.0.0.1:9588}")
    private String ipdUrl;

    @Resource
    private CommonService commonService;
    @Around(value = "execution(* com.hustcad.plm.pdm.doc.controller.TyplmDocumentController.insertDoc(..))")
    public Object createDoc(ProceedingJoinPoint point) throws Throwable {


        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new RuntimeException("属性异常");
        }
        HttpServletRequest request = attributes.getRequest();

        List<MultipartFile> fileList  =(List<MultipartFile>) point.getArgs()[0];

        CreateDocInputDTO createDocInputDTO = (CreateDocInputDTO)JSON.parseObject(request.getParameter("createDocInputDTO"), CreateDocInputDTO.class);
        ObjectStorageDO objectStorageDO = objectStorageService.selectOneByTypeDefName(createDocInputDTO.getDocType());
        if(!"问题处理".equals(createDocInputDTO.getDocType())){
            if (CollUtil.isEmpty(fileList)) {
                return ResponseResult.fail("400","新建文档对象必须上传电子文件");
            }
        }
        SaveDocDTO saveDocDto = new SaveDocDTO();
        FileGroupDTO fileGroupDto = new FileGroupDTO();
        fileGroupDto.setFiles(fileList);
        Integer isMainFile = (Integer) JSON.parseObject(request.getParameter("isMainFile"), Integer.class);
        if (ObjectUtils.isNotEmpty(isMainFile)) {
            fileGroupDto.setIsMainFile(isMainFile);
        }


        CreateDocInputDTO createDocInputDTO2= null;

        boolean isCreateHyperlinks=false;


        //typlmSubFolderLinkService.batchQueryFolderPathVOByIdList()
        if (ObjectUtils.isNotEmpty(createDocInputDTO)) {
            String typeOid = createDocInputDTO.getType();
            if (StringUtils.isNotBlank(typeOid)) {
                this.typlmTypeService.checkTypeInstance(Collections.singletonList(new BigInteger(typeOid)));
            }
            if (StrUtil.isBlank(createDocInputDTO.getContainerType())){
                createDocInputDTO.setContainerType("ty.inteplm.product.CTyPDMLinkProduct");
            }

            /**
             * 判断容器类型是CTyPDMLinkProduct还是CTyProject
             */
            if (createDocInputDTO.getContainerType().equals("ty.inteplm.product.CTyPDMLinkProduct")){
                if (objectStorageDO!=null){
                    PDFProjectVO v = docFolderOperationService.selectPdmIdsByName(objectStorageDO.getContextName());
                    String oId = v.getOId();
                    if (StrUtil.isBlank(createDocInputDTO.getFolderPath())){
                        createDocInputDTO.setFolderPath("/");
                    }

                    String folderId = null;
                    String[] split = objectStorageDO.getFolderPath().split("/");
                    for (int i = 0; i < split.length; i++) {
                        String id=null;
                        if (StrUtil.isBlank(split[i])) {
                            continue;
                        }
                        if (i==1){
                            id= storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                            split[i], "0");
                            if (StrUtil.isNotBlank(id)) {
                                folderId=id;
                            }
                        }else {
                            id = storagePlanningMapper.selectOidByNameAndCid(v.getOId(), split[i], folderId);
                            if (StrUtil.isNotBlank(id)) {
                                folderId= storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                                      split[i], folderId);
                            }

                        }
                        if (StrUtil.isBlank(id)){
                            //创建文件夹
                            SubfolderVO subfolder=new SubfolderVO();
                            subfolder.setName(split[i]);
                            subfolder.setDescription("--系统自动创建--文件夹--");
                            subfolder.setParentOid(i==1?v.getDefaultcabinetoid():folderId);
                            subfolder.setParentOtype(i==1?"ty.inteplm.folder.CTyCabinet":"ty.inteplm.folder.CTySubFolder");
                            SubfolderWebVO subfolderWebVO = typlmSubFolderLinkService.createSubfolder(subfolder);
                            folderId=subfolderWebVO.getOid();
                        }
                    }
                    createDocInputDTO.setContainerName(objectStorageDO.getContextName());
                    createDocInputDTO.setContainerId(oId);
                    createDocInputDTO.setFolderId(folderId);
                    createDocInputDTO.setProductInfoID(oId);
                }
            }else if (createDocInputDTO.getContainerType().equals("ty.inteplm.project.CTyProject")){
                String xxx = storagePlanningMapper.queryExtendedAttributes(createDocInputDTO.getContainerId(), "密级");

                if (StrUtil.isNotBlank(xxx)&&xxx.equals("非密")){
                    if (objectStorageDO!=null){
                        PDFProjectVO v = docFolderOperationService.selectPdmIdsByName(objectStorageDO.getContextName());
                        if (ObjectUtils.isNotEmpty(v)){
                            //将是否创建超链接修改为是
                            isCreateHyperlinks=true;
                            createDocInputDTO2=new CreateDocInputDTO();
                            BeanUtil.copyProperties(createDocInputDTO,createDocInputDTO2);
                            if (StrUtil.isBlank(createDocInputDTO.getFolderPath())){
                                createDocInputDTO.setFolderPath("/");
                            }
                            if (StrUtil.isBlank(createDocInputDTO2.getFolderPath())){
                                createDocInputDTO2.setFolderPath("/");
                                SubfolderDO subfolderDO = docFolderOperationService.obtainTheDirectoryBasedOnItsName(
                                        "超链接", createDocInputDTO2.getContainerId());
                                if (ObjectUtils.isEmpty(subfolderDO)){
                                    String oId = storagePlanningMapper.selectCabinetIdByOid2(createDocInputDTO2.getContainerId());
                                    SubfolderVO subfolder=new SubfolderVO();
                                    subfolder.setName("超链接");
                                    subfolder.setDescription("--系统自动创建--文件夹--");
                                    subfolder.setParentOid(oId);
                                    subfolder.setParentOtype("ty.inteplm.folder.CTyCabinet");
                                    SubfolderWebVO subfolderWebVO = typlmSubFolderLinkService.createSubfolder(subfolder);
                                    createDocInputDTO2.setFolderId(subfolderWebVO.getOid());
                                }{
                                    createDocInputDTO2.setFolderId(subfolderDO.getOid().toString());
                                }

                            }
                            createDocInputDTO.setContainerType("ty.inteplm.product.CTyPDMLinkProduct");
                            createDocInputDTO.setContainerId(v.getOId());
                            createDocInputDTO.setProductInfoID(v.getOId());

                            String folderId = null;
                            String[] split = objectStorageDO.getFolderPath().split("/");
                            for (int i = 0; i < split.length; i++) {
                                String id=null;
                                if (StrUtil.isBlank(split[i])) {
                                    continue;
                                }
                                if (i==1){
                                    id= storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                                    split[i], "0");
                                    if (StrUtil.isNotBlank(id)) {
                                        folderId=id;
                                    }
                                }else {
                                    id = storagePlanningMapper.selectOidByNameAndCid(v.getOId(), split[i], folderId);
                                    if (StrUtil.isNotBlank(id)) {
                                        folderId= storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                                              split[i], folderId);
                                    }

                                }
                                if (StrUtil.isBlank(id)){
                                    //创建文件夹
                                    SubfolderVO subfolder=new SubfolderVO();
                                    subfolder.setName(split[i]);
                                    subfolder.setDescription("--系统自动创建--文件夹--");
                                    subfolder.setParentOid(i==1?v.getDefaultcabinetoid():folderId);
                                    subfolder.setParentOtype(i==1?"ty.inteplm.folder.CTyCabinet":"ty.inteplm.folder.CTySubFolder");
                                    SubfolderWebVO subfolderWebVO = typlmSubFolderLinkService.createSubfolder(subfolder);
                                    folderId=subfolderWebVO.getOid();
                                }
                            }

                            createDocInputDTO.setContainerName(objectStorageDO.getContextName());
                            createDocInputDTO.setFolderId(folderId);
                        }
                    }
                }
            }
            if (StrUtil.isBlank(createDocInputDTO.getFolderPath())){
                createDocInputDTO.setFolderPath("/");
            }
            createDocInputDTO.setNumber(StringUtils.trim(createDocInputDTO.getNumber()));
            createDocInputDTO.setName(StringUtils.trim(createDocInputDTO.getName()));
            this.resetLifecycleStateKey(createDocInputDTO, request);
            saveDocDto.setCreateDocInputDTO(createDocInputDTO);
        }

        Map<String, List<String>> maps = (Map)JSON.parseObject(request.getParameter("ibaAttribute"), Map.class);
        if (CollUtil.isNotEmpty(maps)) {
            saveDocDto.setIbaAttribute(maps);
        }

        List<FileDataVO> fileDataVO = JSON.parseArray(request.getParameter("fileDataVO"), FileDataVO.class);
        if (CollUtil.isNotEmpty(fileDataVO)) {
            saveDocDto.setFileDataVOList(fileDataVO);
        }

        String description = request.getParameter("description");
        if (StringUtils.isNotBlank(description)) {
            List<String> descriptionList = JSON.parseArray(description, String.class);
            fileGroupDto.setDescriptionList(descriptionList);
        }

        saveDocDto.setFileGroupDto(fileGroupDto);
        String workspaceOid = request.getParameter("workspaceId");
        saveDocDto.setWorkspaceOid(workspaceOid);
        DocumentVO docVo = null;
        try {
            CreateDocInputDTO docInputDTO = saveDocDto.getCreateDocInputDTO();
            List<TyAttributeDefMapVO> attrDefMapList = this.typlmTypeService.queryInheritAttrDef(new BigInteger(docInputDTO.getType()), "ty.inteplm.type.CTyTypeDef");
            if(CollUtil.isNotEmpty(attrDefMapList)){
                Optional<TyAttributeDefMapVO> data = attrDefMapList.stream().filter(
                        tyAttributeDefMapVO -> tyAttributeDefMapVO.getName().equals("关联零部件")).findFirst();
                if(data.isPresent()){
                    List<String> list = maps.get("关联零部件");
                    String[] split = list.get(0).split(";");
                    if(!"图纸-客户".equals(createDocInputDTO.getDocType())){
                        if (CollUtil.isNotEmpty(list)) {
                            for (String item : split) {
                                String partNumber = item.split(",")[0];
                                PartDO partDO = rtPartMapper.queryLatestPartByNumberAndView(partNumber, "Design", "RELEASED");//查询已发布版本
                                if (partDO == null) {
                                    partDO = rtPartMapper.queryLatestPartByNumberAndView(partNumber, "Design", "EffectiveNot");
                                    if(partDO==null){
                                        throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                                                "零部件在系统中不存在已生效版本不允许关联！:" + partNumber);
                                    }
                                }
                            }
                        }
                    }

                    docVo = typlmDocumentService.insertDoc(saveDocDto);
                    docService.batchPartDescribeAndReferenceLink(docVo, list);
                }else {
                    docVo = typlmDocumentService.insertDoc(saveDocDto);
                }
            }else {
                docVo = typlmDocumentService.insertDoc(saveDocDto);
            }
            String docOidStr = docVo.getOid();
            if (StringUtil.isNotEmpty(docOidStr) && docOidStr.contains(":")) {
                docOidStr = docOidStr.split(":")[1];
            }
            docVo.setDocOid(docOidStr);
            //判断是否创建超链接
            if (isCreateHyperlinks){
                //创建超链接
                HyperlinkDTO hyperlinkDTO = docFolderOperationService.assignmentToHyperlinkDTO(createDocInputDTO2, docVo);
                List<HyperlinkDTO> l=new ArrayList<>();
                l.add(hyperlinkDTO);
                typlmHyperlinkService.batchCreateHyperlink(l);
            }
            if(maps.containsKey("AssociatedProjectTasks") && maps.containsKey("RelatedProject")){
                List<String> jobIds = maps.get("AssociatedProjectTasks");
                List<String> relatedProject = maps.get("RelatedProject");
                if(CollUtil.isNotEmpty(jobIds) && CollUtil.isNotEmpty(relatedProject)){
                    String jobOid = jobIds.get(0);
                    String relatedProjectId = relatedProject.get(0);
                    createDocAndJobLink(jobOid, relatedProjectId,docVo, createDocInputDTO.getDocType());
                }
            }
            this.typlmLogger.info(new CTyEntityBaseDO(CommonUtil.stringToBigInteger(docOidStr), docVo.getOtype()), LogEventEnum.CRATE_OBJECT);
            return ResponseResult.success(docVo);
        } catch (Exception var13) {
            AuditLogDO auditLogDO = new AuditLogDO();
            auditLogDO.setObjotype("ty.inteplm.doc.CTyDoc");
            auditLogDO.setTargettype(createDocInputDTO.getType());
            auditLogDO.setContaineroidStr(createDocInputDTO.getContainerId());
            auditLogDO.setContainerotype(createDocInputDTO.getContainerType());
            auditLogDO.setTargetname(createDocInputDTO.getName());
            auditLogDO.setTargetnumber(createDocInputDTO.getNumber());
            auditLogDO.setLifecyclestatekey(createDocInputDTO.getLifecycleStateKey());
            auditLogDO.setLifecyclestageotype(createDocInputDTO.getLifecycleStateKey());
            auditLogDO.setTargetsecuritylabels(createDocInputDTO.getSecurity());
            this.typlmLogger.errorInfo(LogEventEnum.CRATE_OBJECT, auditLogDO, var13);
            throw var13;
        }
    }

    private void createDocAndJobLink(String jobOid, String relatedProjectId, DocumentVO documentVO, String typeName) {
        try {
            if(StringUtils.isBlank(jobOid) || StringUtils.isBlank(relatedProjectId)){
                return;
            }
            String url = ipdUrl+ "/api/v1/outrule/queryOutRuleByPage";

            UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(url)
                    .queryParam("jobOid", jobOid)
                    .queryParam("pageNum", 1)
                    .queryParam("pageSize", 999)
                    .queryParam("name", "");
            String responseData = commonService.sendGetRequestToIPD(urlBuilder.toUriString());
            JSONObject responseJson = JSONObject.parseObject(responseData);
            JSONArray data = responseJson.getJSONArray("data");
            if(CollUtil.isEmpty( data)){
                return;
            }
            Optional<JSONObject> optional = data.stream().map(item -> (JSONObject) item).filter(item -> typeName.equals(item.getString("ruletypeDisplayName"))).findFirst();
            if (optional.isPresent()) {
                JSONObject outRule = optional.get();
                JSONObject json = (JSONObject)JSONObject.toJSON(documentVO);
                JSONObject batchInsetDocVO = new JSONObject();
                batchInsetDocVO.put("docList", Collections.singletonList(json));
                batchInsetDocVO.put("docOtype", documentVO.getOtype());
                batchInsetDocVO.put("type", "OUT");
                batchInsetDocVO.put("localRepositoryUid", "javaPDM");
                batchInsetDocVO.put("outputRuleOid", outRule.get("oid"));
                batchInsetDocVO.put("parentNodeOid", jobOid);
                batchInsetDocVO.put("parentNodeOtype", TableTypeConstrant.TY_JOB_OTYPE);
                batchInsetDocVO.put("projectOid", relatedProjectId);
                String addLinkUrl = ipdUrl+ "/api/v1/javapdmremote/insertRemoteDoc";
                String responseDate = commonService.sendPutRequestToIPD(addLinkUrl, batchInsetDocVO.toJSONString());
                log.info("============开始创建文档超链接完成,执行结果===================>>:{}", responseDate);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void resetLifecycleStateKey(CreateDocInputDTO createDocInputDTO, HttpServletRequest request) {
        if (!StringUtils.isNotBlank(createDocInputDTO.getLifecycleStateKey())) {
            JSONObject jsonObject = JSON.parseObject(request.getParameter("createDocInputDTO"));
            String lifecycleState = jsonObject.getString("lifecycleState");
            if (StringUtils.isNotBlank(lifecycleState)) {
                createDocInputDTO.setLifecycleStateKey(lifecycleState);
            }

        }
    }


//    public void batchAddPartDescribeLink(List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTOList) {
//        Map<BigInteger, CTyEntityBaseDO> entityMap = this.judgeAddOrDeletePartDescribeLinkParam(batchAddPartDescribeLinkDTOList, false);
//        List<PartDescribeLinkDO> partDescribeLinkDOS = new LinkedList<>();
//        ((Map)batchAddPartDescribeLinkDTOList.stream().collect(Collectors.groupingBy(BatchAddPartDescribeLinkDTO::getOtype))).forEach((otype, list) -> {
//            Iterator var7;
//            BatchAddPartDescribeLinkDTO batchAddPartDescribeLinkDTO;
//            switch (otype) {
//                case "ty.inteplm.part.CTyPart":
//                    var7 = list.iterator();
//
//                    while(var7.hasNext()) {
//                        batchAddPartDescribeLinkDTO = (BatchAddPartDescribeLinkDTO)var7.next();
//                        batchAddPartDescribeLinkDTO.getRefObj().stream().filter((vo) -> {
//                            return "ty.inteplm.doc.CTyDoc".equalsIgnoreCase(vo.getOtype());
//                        }).forEach((vo) -> {
//                            partDescribeLinkDOS.add(typlmPartDescribeLinkService.getPartDescribeLinkDO(batchAddPartDescribeLinkDTO.getOid(), batchAddPartDescribeLinkDTO.getOtype(), vo.getOid(), vo.getOtype()));
//                            CTyEntityBaseDO cTyEntityBaseDO = (CTyEntityBaseDO)entityMap.get(vo.getOid());
//                            DocDO doc = (DocDO)cTyEntityBaseDO;
//                            if ("wrk".equalsIgnoreCase(doc.getLockstateinfo())) {
//                                partDescribeLinkDOS.add(typlmPartDescribeLinkService.getPartDescribeLinkDO(batchAddPartDescribeLinkDTO.getOid(), batchAddPartDescribeLinkDTO.getOtype(), doc.getSourceiterationoid(), doc.getOtype()));
//                            }
//
//                        });
//                    }
//
//                    return;
//                case "ty.inteplm.doc.CTyDoc":
//                    var7 = list.iterator();
//
//                    while(var7.hasNext()) {
//                        batchAddPartDescribeLinkDTO = (BatchAddPartDescribeLinkDTO)var7.next();
//                        batchAddPartDescribeLinkDTO.getRefObj().stream().filter((vo) -> {
//                            return "ty.inteplm.part.CTyPart".equalsIgnoreCase(vo.getOtype());
//                        }).forEach((vo) -> {
//                            partDescribeLinkDOS.add(typlmPartDescribeLinkService.getPartDescribeLinkDO(vo.getOid(), vo.getOtype(), batchAddPartDescribeLinkDTO.getOid(), batchAddPartDescribeLinkDTO.getOtype()));
//                            CTyEntityBaseDO cTyEntityBaseDO = (CTyEntityBaseDO)entityMap.get(vo.getOid());
//                            PartDO part = (PartDO)cTyEntityBaseDO;
//                            if ("wrk".equalsIgnoreCase(part.getLockstateinfo())) {
//                                partDescribeLinkDOS.add(typlmPartDescribeLinkService.getPartDescribeLinkDO(part.getSourceiterationoid(), part.getOtype(), batchAddPartDescribeLinkDTO.getOid(), batchAddPartDescribeLinkDTO.getOtype()));
//                            }
//
//                        });
//                    }
//            }
//
//        });
//        if (CollUtil.isNotEmpty(partDescribeLinkDOS)) {
//            ConcurrentSkipListMap<String, PartDescribeLinkDO> collect = (ConcurrentSkipListMap)partDescribeLinkDOS.parallelStream().collect(Collectors.toMap((o) -> {
//                return o.getAoid() + "," + o.getBoid();
//            }, Function.identity(), (oldObj, newObj) -> {
//                return oldObj;
//            }, ConcurrentSkipListMap::new));
//            List<PartDescribeLinkDO> exsitLinkDOList = this.typlmPartDescribeLinkMapper.batchQueryPartDescribeLinkByAoidBoid(new ArrayList(collect.values()));
//            List<MessageException> errs = new ArrayList();
//            if (CollUtil.isNotEmpty(exsitLinkDOList)) {
//                List<CTyEntityBaseDO> cTyEntityBaseDOS = new ArrayList();
//                Iterator var8 = exsitLinkDOList.iterator();
//
//                while(var8.hasNext()) {
//                    PartDescribeLinkDO partDescribeLinkDO = (PartDescribeLinkDO)var8.next();
//                    cTyEntityBaseDOS.add(new CTyEntityBaseDO(partDescribeLinkDO.getAoid(), partDescribeLinkDO.getAotype()));
//                    cTyEntityBaseDOS.add(new CTyEntityBaseDO(partDescribeLinkDO.getBoid(), partDescribeLinkDO.getBotype()));
//                }
//
//                Map<String, String> entityDisplayNameList = CommonUtil.getEntityDisplayNameList((List)cTyEntityBaseDOS.stream().distinct().collect(Collectors.toList()));
//                Iterator var12 = exsitLinkDOList.iterator();
//
//                while(var12.hasNext()) {
//                    PartDescribeLinkDO partDescribeLinkDO = (PartDescribeLinkDO)var12.next();
//                    errs.add(PartBomErrorCodeEnum.PARTDESCRIBELINK_ALREADY_EXSITS.getException(new Object[]{entityDisplayNameList.getOrDefault("ty.inteplm.part.CTyPart:" + partDescribeLinkDO.getAoid(), String.valueOf(partDescribeLinkDO.getAoid())), entityDisplayNameList.getOrDefault("ty.inteplm.doc.CTyDoc:" + partDescribeLinkDO.getBoid(), String.valueOf(partDescribeLinkDO.getBoid()))}));
//                }
//
//                throw new MessageException((List)errs.stream().distinct().collect(Collectors.toList()));
//            }
//
//            this.typlmEntityBaseService.batchInsertWithCommit(collect.values());
//        }
//
//    }
//
//    private Map<BigInteger, CTyEntityBaseDO> judgeAddOrDeletePartDescribeLinkParam(List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTOList, boolean isDelete) {
//        ArgumentUtils.checkArgumentNull(batchAddPartDescribeLinkDTOList, "batchAddPartDescribeLinkDTO");
//        batchAddPartDescribeLinkDTOList.forEach((vo) -> {
//            ArgumentUtils.checkArgumentNull(vo.getOid(), "batchAddPartDescribeLinkDTO.oid");
//            ArgumentUtils.checkArgumentNull(vo.getOtype(), "batchAddPartDescribeLinkDTO.otype");
//            ArgumentUtils.checkArgumentNull(vo.getRefObj(), "batchAddPartDescribeLinkDTO.refObjOid");
//        });
//        List<CTyEntityBaseDO> entityBaseDOS = new ArrayList<>();
//        (batchAddPartDescribeLinkDTOList.stream().flatMap((vo) -> {
//            return Stream.concat(Stream.of(vo), vo.getRefObj().stream().map((ref) -> {
//                return new BatchAddPartDescribeLinkDTO(ref.getOid(), ref.getOtype(), null);
//            }));
//        }).collect(Collectors.groupingBy(BatchAddPartDescribeLinkDTO::getOtype, Collectors.mapping(BatchAddPartDescribeLinkDTO::getOid, Collectors.toList())))).forEach((otype, oidList) -> {
//            entityBaseDOS.addAll(CommonUtil.batchQueryEntityList(oidList, otype));
//        });
//        if (BooleanUtils.isFalse(isDelete)) {
//            this.typlmCheckCollectionObjService.checkCollectObjMajorAndLatestVersion(entityBaseDOS);
//        }
//
//        this.addWrkEntity(batchAddPartDescribeLinkDTOList, entityBaseDOS);
//        Stream var10000 = entityBaseDOS.stream();
//        ITyTyped.class.getClass();
//        List<BigInteger> typeOids = (List)var10000.filter(ITyTyped.class::isInstance).map((vo) -> {
//            return ((ITyTyped)vo).getTypeoid();
//        }).collect(Collectors.toList());
//        List<TypeVueVO> typeDOS = this.typlmTypeService.queryTypeByIds(typeOids);
//        Map<BigInteger, TypeVueVO> typeDOMap = (Map)typeDOS.stream().collect(Collectors.toMap(TypeDO::getOid, (item) -> {
//            return item;
//        }, (k1, k2) -> {
//            return k1;
//        }));
//        List<MessageException> errs = new ArrayList();
//        Map<BigInteger, CTyEntityBaseDO> entityMap = (Map)entityBaseDOS.stream().collect(Collectors.toMap(CTyEntityBaseDO::getOid, (item) -> {
//            return item;
//        }, (k1, k2) -> {
//            return k1;
//        }));
//
//        BatchAddPartDescribeLinkDTO batchAddPartDescribeLinkDTO;
//        for(Iterator var9 = batchAddPartDescribeLinkDTOList.iterator(); var9.hasNext(); batchAddPartDescribeLinkDTO.getRefObj().forEach((vo) -> {
//            if (!entityMap.containsKey(vo.getOid())) {
//                errs.add(SystemErrorCodeEnum.BIZ_OBJECT_NOT_FOUND.getException(new Object[]{vo.getOid()}));
//            }
//
//        })) {
//            batchAddPartDescribeLinkDTO = (BatchAddPartDescribeLinkDTO)var9.next();
//            if (!entityMap.containsKey(batchAddPartDescribeLinkDTO.getOid())) {
//                errs.add(SystemErrorCodeEnum.BIZ_OBJECT_NOT_FOUND.getException(new Object[]{batchAddPartDescribeLinkDTO.getOid()}));
//            } else {
//                CTyEntityBaseDO cTyEntityBaseDO = (CTyEntityBaseDO)entityMap.get(batchAddPartDescribeLinkDTO.getOid());
//                if (cTyEntityBaseDO instanceof ITyLockable && !"wrk".equalsIgnoreCase(((ITyLockable)cTyEntityBaseDO).getLockstateinfo())) {
//                    errs.add(
//                            ConfiguredBomErrorCodeEnum.CONFIGUREDBOM_OBJECT_NOT_WRK.getException(new Object[]{CommonUtil.getEntityDisplayName(cTyEntityBaseDO)}));
//                }
//
//                Map<String, String> errMap = new HashMap();
//                if ("ty.inteplm.part.CTyPart".equalsIgnoreCase(batchAddPartDescribeLinkDTO.getOtype()) && BooleanUtils.isFalse(isDelete)) {
//                    PartDO partDO = (PartDO)cTyEntityBaseDO;
//                    TypeVueVO typeVueVO = (TypeVueVO)typeDOMap.get(partDO.getTypeoid());
//                    List<String> allowInthidList = this.typlmAssociationConstraintService.queryTypeInthidByLinkAndAType("ty.inteplm.part.CTyPartDescribeLink", typeVueVO.getInthid());
//                    batchAddPartDescribeLinkDTO.getRefObj().forEach((vo) -> {
//                        CTyEntityBaseDO doc = (CTyEntityBaseDO)entityMap.get(vo.getOid());
//                        TypeVueVO docType = (TypeVueVO)typeDOMap.get(((ITyTyped)doc).getTypeoid());
//                        if (!ObjectUtils.isNotEmpty(allowInthidList) || !allowInthidList.stream().anyMatch((item) -> {
//                            return docType.getInthid().equals(item) || docType.getInthid().startsWith(item + "|");
//                        })) {
//                            if (errMap.containsKey(typeVueVO.getDisplayName()) && !Arrays.asList(((String)errMap.get(typeVueVO.getDisplayName())).split(", ")).contains(docType.getDisplayName())) {
//                                errMap.put(typeVueVO.getDisplayName(), (String)errMap.get(typeVueVO.getDisplayName()) + ", " + docType.getDisplayName());
//                            } else {
//                                errMap.put(typeVueVO.getDisplayName(), docType.getDisplayName());
//                            }
//                        }
//
//                    });
//                    if (CollUtil.isNotEmpty(errMap)) {
//                        errMap.forEach((key, value) -> {
//                            errs.add(PartBomErrorCodeEnum.TYPE_CAN_NOT_ADD_PARTDESCRIBELINK.getException(new Object[]{key, value}));
//                        });
//                    }
//                }
//            }
//        }
//
//        if (CollUtil.isNotEmpty(errs)) {
//            throw new MessageException(errs);
//        } else {
//            return entityMap;
//        }
//    }
//
//    private void addWrkEntity(List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTOList, List<CTyEntityBaseDO> entityBaseDOS) {
//        List<BigInteger> coOids = (List)entityBaseDOS.stream().filter((vo) -> {
//            return vo instanceof ITyLockable && "wrk".equalsIgnoreCase(((ITyLockable)vo).getLockstateinfo());
//        }).map((vo) -> {
//            return ((ITyIterated)vo).getSourceiterationoid();
//        }).collect(Collectors.toList());
//        List<CTyEntityBaseDO> noWrkCoEntityList = (List)entityBaseDOS.stream().filter((vo) -> {
//            return vo instanceof ITyLockable && "c/o".equalsIgnoreCase(((ITyLockable)vo).getLockstateinfo());
//        }).filter((s) -> {
//            return !coOids.contains(s.getOid());
//        }).collect(Collectors.toList());
//        if (CollUtil.isNotEmpty(noWrkCoEntityList)) {
//            List<BigInteger> noWrkCoOids = (List)noWrkCoEntityList.stream().map(CTyEntityBaseDO::getOid).collect(Collectors.toList());
//            List<CTyEntityBaseDO> wrkCtyEntityList = new ArrayList();
//            ((Map)noWrkCoEntityList.stream().collect(Collectors.groupingBy(CTyEntityBaseDO::getOtype, Collectors.mapping(CTyEntityBaseDO::getOid, Collectors.toList())))).forEach((key, value) -> {
//                wrkCtyEntityList.addAll(CommonUtil.getWrkByCoIds(key, value));
//            });
//            Stream var10000 = wrkCtyEntityList.stream();
//            ITyLockable.class.getClass();
//            Map<BigInteger, CTyEntityBaseDO> coWrkMap = (Map)var10000.filter(ITyLockable.class::isInstance).collect(Collectors.toMap((vo) -> {
//                return ((ITyIterated)vo).getSourceiterationoid();
//            }, (item) -> {
//                return item;
//            }, (k1, k2) -> {
//                return k1;
//            }));
//            Iterator var8 = batchAddPartDescribeLinkDTOList.iterator();
//
//            while(var8.hasNext()) {
//                BatchAddPartDescribeLinkDTO batchAddPartDescribeLinkDTO = (BatchAddPartDescribeLinkDTO)var8.next();
//                List<IdentifierEntity> refObj = batchAddPartDescribeLinkDTO.getRefObj();
//                var10000 = refObj.stream().map(IdentifierEntity::getOid);
//                noWrkCoOids.getClass();
//                List<BigInteger> coList = (List)var10000.filter(noWrkCoOids::contains).collect(Collectors.toList());
//                Iterator var12 = coList.iterator();
//
//                while(var12.hasNext()) {
//                    BigInteger bigInteger = (BigInteger)var12.next();
//                    CTyEntityBaseDO cTyEntityBaseDO = (CTyEntityBaseDO)coWrkMap.get(bigInteger);
//                    refObj.add(new IdentifierEntity(cTyEntityBaseDO.getOid(), cTyEntityBaseDO.getOtype()));
//                }
//            }
//
//            entityBaseDOS.addAll(wrkCtyEntityList);
//        }
//
//    }

}
